let jwt = require('../../utils/jwt')
let mgdb = require('../../utils/mgdb')

module.exports = (req, res, next) => {
    // 公共参数
    req.query._page = req.query._page ? req.query._page - 1 : require('../../config/global')._page
    req.query._limit = req.query._limit ? req.query._limit : require('../../config/global')._limit
    req.query.q = req.query.a ? req.query.a : require('../../config/global').q
    req.query._sort = req.query._sort ? req.query._sort : require('../../config/global')._sort

    req.body._page = req.body._page ? req.body._page - 1 : require('../../config/global')._page
    req.body._limit = req.body._limit ? req.body._limit : require('../../config/global')._limit
    req.body.q = req.body.a ? req.query.a : require('../../config/global').q
    req.body._sort = req.body._sort ? req.body._sort : require('../../config/global')._sort

    req.header._page = req.header._page ? req.header._page - 1 : require('../../config/global')._page
    req.header._limit = req.header._limit ? req.header._limit : require('../../config/global')._limit
    req.header.q = req.header.a ? req.header.a : require('../../config/global').q
    req.header._sort = req.header._sort ? req.header._sort : require('../../config/global')._sort

    req.mgdb = mgdb
    //token检验
    if (/login|reg|goods|banner/.test(req.url)) {
        next();
    } else {
        let token = req.headers.token || req.body.token || req.query.token
        jwt.verify(token).then(
            decode => {
                req.query.decode = decode
                next()
            }
        ).catch(
            message => res.send({ err: 2, msg: 'token过期或失效' + message })
        )
    }
}